package com.itheima.aop;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class RecordTimeAspect {
    //@PointCut切入点表达式, 抽取公共的表达式
    @Pointcut("execution(* com.itheima..service.impl.DeptServiceImpl.*(..))")
    public void pc() {
    }

    //@Around("execution(* com.itheima.service.impl.DeptServiceImpl.*(..))")
    public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
        ///记录方法执行开始时间
        //@Before
        long start = System.currentTimeMillis();
        try {
            //执行原始方法
            Object result = joinPoint.proceed();
            //记录方法执行结束时间
            //@AfterReturning
            long end = System.currentTimeMillis();
            log.info("方法执行耗时：{}毫秒", end - start);
            return result;
        } catch (Throwable e) {
            //AfterThrowing
            throw new RuntimeException(e);
        } finally {
            //@After
        }
    }

    /**
     * 前置通知
     */
    @Before("pc()")
    public void before() {
        log.info("方法执行开始");
    }

    /**
     * 返回通知
     */
    @AfterReturning("pc()")
    public void afterReturning(JoinPoint JoinPoint) {
        //joinPoint切入点
        log.info("方法执行结束");
    }

    /**
     * 异常通知
     */
    @AfterThrowing("pc()")
    public void afterThrowing(JoinPoint joinPoint) {
        log.info("方法执行异常");
    }

    /**
     * 最终通知,后置通知
     */
    @After("pc()")
    public void after(JoinPoint joinPoint) {
        log.info("方法执行结束，不管是否发生异常都会执行");
    }

}
